package util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @program: rabbitmq-demo1
 * @description: 工具类
 * @author: luolidong
 * @create: 2021-06-14 22:04
 * @version: 1.0
 */
public class ConnectionUtil {
    private static ConnectionFactory connectionFactory;

    static {//类加载时只执行一次
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.247.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/ems");//虚拟主机
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("ems");
    }

    public static Connection createConnection(){
        try {
//        获取连接
            return connectionFactory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void closeConnectionChannel(Channel channel,Connection connection){
        try {
            if(channel!=null) channel.close();
            if(connection!=null) connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
